<template>
  <view class="container">
    <!-- 用于显示摄像头画面的 canvas -->
    <canvas id="qr-canvas" style="width: 100%; height: 80vh"></canvas>
    <button @click="startScan" style="top: -50px">开始扫描2</button>
    <button @click="stopScan">停止扫描2</button>
  </view>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { BrowserQRCodeReader } from '@zxing/library';

import {
  sendLog, // 输出日志到本地
  viewLog, // 打印和输出日志到本地
  getEnvironmentType // 运行环境
} from '@/common/js/utils/index.js';

// 定义响应式变量
const codeReader = ref(null); // ZXing 二维码读取器实例
const isScanning = ref(false); // 是否正在扫描

// 初始化 ZXing 二维码读取器
onMounted(() => {
  codeReader.value = new BrowserQRCodeReader();
});

// 开始扫描
const startScan = async () => {
  if (isScanning.value) return; // 防止重复启动
  isScanning.value = true;

  try {
    // 从摄像头设备获取视频流并开始解码
    const result = await codeReader.value.decodeFromInputVideoDevice(undefined, 'qr-canvas');
    console.log('扫描结果:', result.text);

    viewLog({
      scan_res: result.text
    });

    // 显示扫描结果
    uni.showModal({
      title: '扫描结果',
      content: result.text,
      showCancel: false
    });
  } catch (error) {
    viewLog({
      scan_error: error.message
    });
    console.error('扫描失败:', error);
    uni.showToast({
      title: '扫描失败，请重试',
      icon: 'none'
    });
  } finally {
    isScanning.value = false;
  }
};

// 停止扫描
const stopScan = () => {
  if (codeReader.value) {
    codeReader.value.reset(); // 重置扫描器
    isScanning.value = false;
  }
};

// 页面销毁时停止扫描
onBeforeUnmount(() => {
  stopScan();
});
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
</style>
